// login & register
const express = require('express')
const router = express.Router()
const passport = require('passport')
const Profile = require('../../models/Profile')

// $route POST api/profiles/add
// @desc 添加
// @access Private
router.post('/add', passport.authenticate('jwt', {session: false}), (req, res) => {
    const {type, describe, income, expend, cash, remark} = req.body
    const profileFields = {type, describe, income, expend, cash, remark}
    new Profile(profileFields).save().then(profile => {
        res.json(profile)
    })
})


// $route GET api/profiles
// @desc 获取信息接口
// @access Private
router.get('/', passport.authenticate('jwt', {session: false}), (req, res) => {
    Profile.find()
    .then(profiles => {
        if (!profiles) return res.status(404).json({msg: '没有内容'})
        res.json(profiles)
    })
    .catch(err => res.status(500).json({msg: '获取信息失败'}))
})

// $route GET api/profiles/:id
// @desc 获取单个信息接口
// @access Private
router.get('/:id', passport.authenticate('jwt', {session: false}), (req, res) => {
    Profile.findOne({_id: req.params.id})
    .then(profile => {
        if (!profile) return res.status(404).json({msg: '不存在'})
        res.json(profile)
    })
    .catch(err => res.status(500).json({msg: '获取信息失败'}))
})


// $route POST api/profiles/edit/:id
// @desc 编辑
// @access Private
router.post('/edit/:id', passport.authenticate('jwt', {session: false}), (req, res) => {
    const {type, describe, income, expend, cash, remark} = req.body
    const profileFields = {type, describe, income, expend, cash, remark}
    Profile.findOneAndUpdate({_id: req.params.id},{$set: profileFields},{new: true}).then(profile => {
        if (!profile) return res.status(404).json({msg: '不存在'})
        res.json(profile)
    })
})

// $route POST api/profiles/:id
// @desc 删除信息
// @access Private
router.delete('/:id', passport.authenticate('jwt', {session: false}), (req, res) => {
    Profile.findOneAndRemove({_id: req.params.id}).then(profile => {
        if (!profile) return res.status(404).json({msg: '不存在'})
        res.json(profile)
    }).catch(err => res.status(500).json({msg: '数据库删除异常'}))
})

module.exports = router